import { Component } from 'react';

import { Button,Boxs } from 'saltui';
const { HBox,Box } = Boxs;
import Form from 'components/form/form';
let FlowCommon ;

export default class PageHome extends Component {

  constructor(props) {
    super(props);
    var form = props.form;
    var data = props.data;
    var status = props.status;
    var context = document.getElementById("context").value;

    let module = props.module;
    FlowCommon = require('pages/flow_common/'+module);
    // var itemParam = 
    this.state = {
      module:props.module,
      status: status,
      fieldControll:props.fieldControll,
      urlPrev: context + '/dingisv/api/common/viewImage?fid=',
      calc:[],
      itemParam:{
        readOnly:false,
        required:false,
        title:'',
        value:'',
        itemType:'',
        id:'',
        key:''
      },
      commentList:[],
      subModel:[]
    };
    
  }


  //流程控制表单字段显示
  fieldControllFormat(field,fieldControll){
    // let isHidden = null;
    // let required = null;
    // let readOnly = null;
    let status = null;
    if(fieldControll){
      let hiddenFields = fieldControll.hiddenFields;
      let mustFields = fieldControll.mustFields;
      let showFields = fieldControll.showFields;
      let editFields = fieldControll.editFields;

      if(hiddenFields){ //是否隐藏
        if(hiddenFields.indexOf(field)>=0){//是否包含字段
          status = "hidden";
          return status;
        }
      }


      if(showFields){ //是否只读
        if(showFields.indexOf(field)>=0){//是否包含字段
          status = "show";
          return status;
        }
      }

      if(editFields){ //是否可编辑
        if(editFields.indexOf(field)>=0){//是否包含字段
          status = "edit";
          if(mustFields){ //是否必须
            if(mustFields.indexOf(field)>=0){//是否包含字段
              status = "edit&must";
              return status;
            }
          }
          return status;
        }
      }
    } 
  }

  //加载组件
  loadComponet(){
    let t = this;
    var form = this.props.form; //表单元素
    var status = this.props.status; //判断是否能选择,0新增，1修改,2查看
    var data = this.props.data; //数据
    var subTbl = data.subTbl;//子表
    //var dataType = this.props.dataType;//数据类型，main:主表，sub：子表，
    var itemParam = {};  //元素参数
    var id = form.id;
    itemParam.id=id;
    var title = form.itemTitle; //标题
    itemParam.title=title;
    var key = form.itemCode; //表字段;
    itemParam.key=key;
    var itemType = form.itemType; //类型
    itemParam.itemType=itemType;

    itemParam.isHidden = false;//默认不隐藏

    //判断字段属性
    let fieldControllJson = this.props.fieldControll;
    var subtableReadonly = false;
    if(fieldControllJson){

      var subtableReadonlyStr = "";
      if(fieldControllJson.subtable){
        subtableReadonlyStr=fieldControllJson.subtable;
      }
      if(subtableReadonlyStr.indexOf(form.tblId)>=0){
        subtableReadonly = true;
      }
    }

    if(status==2){
      subtableReadonly = true;
    }
    itemParam.subtableReadonly = subtableReadonly;
    var subForm = form.children;
    var value = this.dealwithSubForm(subForm,itemParam,subTbl);
    data.subTbl = subTbl;
    itemParam.show = true;
    itemParam.value = value;
    itemParam.detailAction = form.detailAction;//添加事件名字
     //处理特有按钮事件
    if(typeof FlowCommon.dealwithCommonFormParam === "function"){
      itemParam = FlowCommon.dealwithCommonFormParam(itemParam,this);
    }

    this.setState({
      itemParam:itemParam
    })
    this.props.onChange(data);
  }

  componentDidMount() {
     this.loadComponet();
  }

  //处理子表数据
  dealwithSubForm(subForm,itemParam,subTbl){
    var subFormList = [];
    
    var itemCode = itemParam.key;
    var value = [];
    if(subTbl.length>0){
      for(var i=0;i<subTbl.length;i++) { 
        var item = subTbl[i];
        if(item.subTblName==itemCode){
          var subTblData = item.subTblData;
          if(subTblData.length>0){
            for(var j=0;j<subTblData.length;j++) { 
              value.push({mainTblData:subTblData[j],mainTblName:itemCode});
              var subForm1 = {show:true,form:subForm};
              subFormList.push(subForm1);
            }
          }else{
            var subForm2 = {show:true,form:subForm};
            value.push({mainTblData:[],mainTblName:itemCode});
            subFormList.push(subForm2);
          }
          break;
        }
      }
    }
    if(subFormList.length>0){
      itemParam.subForm = subFormList;
    }else{
      var subForm3 = {show:true,form:subForm};
      subFormList.push(subForm3);
      itemParam.subForm = subFormList;
      value.push({mainTblData:[],mainTblName:itemCode});
      subTbl.push({subTblData:[],subTblName:itemCode});
    }
    return value;
  }


  //修改data数据
  editData(itemCode,value,data){
    var mainTblData = data.mainTblData;
    mainTblData.map(function(item,index){
      if(item.key==itemCode){
        item.value = value;
      }
    });
    return data;
  }
  //表单提交以前校验
  saveBefore(type,data,succeedCall,failuredCall){
    if(data.startTime<new Date().format("yyyy-MM-dd HH:mm")){
      failuredCall("开始时间不能小于当前时间");
    }else if(data.startTime>=data.endTime){
      failuredCall("开始时间不能大于等于结束时间");
    }else succeedCall();
  }

  //子表操作修改
  changeSub(itemSubTbl,subTblNo,value,subItem){
    var itemParam = this.state.itemParam;
    var data = this.props.data;
    var subTblList = data.subTbl;//子表
    // if(isInit){//初始化
    //   var subModel = [];
    //   if(value.mainTblData.length>0){
    //     subModel = value.mainTblData;
    //   }
    //   this.setState({
    //     subModel:subModel
    //   });
    // }
    
    this.dealwithSubData(subTblList,subTblNo,value);
    if(subItem){//当子表的数据改变回调回来的子表详情itemparam不为空时
      this.props.onChange(data,subItem);
    }else{
      this.props.onChange(data);
    }
    
    
  }

  //处理子表数据
  dealwithSubData(subTblList,subTblNo,value){
    if(subTblList.length>0){//子表数据为空
      for(var j=0; j<subTblList.length; j++){
        if(value.mainTblName == subTblList[j].subTblName){
           subTblList[j].subTblData[subTblNo] = value.mainTblData;
           break;
        }
      }
    }
  }

  //重新加载组件
  reloadItemParam(itemNew){
    if(itemNew != null && itemNew != undefined && Array.isArray(itemNew)){
      var itemParam = this.state.itemParam;
      for(var i=0; i<itemNew.length; i++){
        var key = itemNew[i].key;
        itemParam[key] = itemNew[i].value;
      }
      this.setState({
        itemParam:itemParam
      });
    }
  }

  //重新加载子表各字段
  reloadSubItemParam(itemNew){
    if(itemNew != null && itemNew != undefined && Array.isArray(itemNew)){
      for(var i=0; i<itemNew.length; i++){
        var fieldCode = itemNew[i].uniqueName;
        var value = itemNew[i].value;
        var itemParam = this.state.itemParam;
        for(var j=0; j<itemParam.subForm.length; j++){
          if(this.refs[fieldCode+'_'+j]){
            this.refs[fieldCode+'_'+j].reloadItemParam(value);
          }
        }
      }
    }
  }

  //获取字段的itemParam属性
  getItemParam(){
    var itemParam = this.state.itemParam;
    return itemParam;
  }

  //获取子表各字段的itemParam属性
  getSubItemParam(fieldCode){
    var subItemParam  = [];
    var itemParam = this.state.itemParam;
    for(var i=0; i<itemParam.subForm.length; i++){
      if(fieldCode && this.refs[fieldCode+'_'+i]){
          var itemParamItem= this.refs[fieldCode+'_'+i].getItemParam();
          if(itemParamItem != null){
            subItemParam.push(itemParamItem);
          }
      }
    }
    return subItemParam;
  }

  //明细显示隐藏（全部）
  detailShowAll(){
    var itemParam = this.state.itemParam;
    itemParam.show = !itemParam.show;
    this.setState({
      itemParam:itemParam
    });
  }

  //明细显示隐藏
  detailShow(i,show){
    var itemParam = this.state.itemParam;
    itemParam.subForm[i].show = !show;
     this.setState({
      itemParam:itemParam,
   });
  }

  //明细删除
  detailDel(i,e){
    e.stopPropagation();
    var itemParam = this.state.itemParam;
    var subForm = itemParam.subForm;
    subForm.splice(i,1);
    itemParam.value.splice(i,1);
   // itemParam.subForm = subForm;
    var data = this.props.data;
    var subTblList = data.subTbl;
    for(var j=0; j<subTblList.length; j++){
      if(subTblList[j].subTblName == itemParam.key){
        var subTblData = subTblList[j].subTblData;
        subTblData.splice(i,1);
        subTblList[j].subTblData=subTblData;
      }
    }
    this.setState({
      itemParam:itemParam,
    },function(data){
     // this.forceUpdate();
     var itemParamList = this.state.itemParam.value;
     for(var m=0 ;m<itemParamList.length; m++){
       var tblData = itemParamList[m].mainTblData;
       var tblName = itemParamList[m].mainTblName;
       for(var n=0 ;n<tblData.length; n++){
          var key = tblData[n].key;
          var value = tblData[n].value;
          if(this.refs[tblName+'_'+key+'_'+m]){
            this.refs[tblName+'_'+key+'_'+m].reloadItemParam([{'key':'value','value':value}]);
          }
          
       }
     }
      // var refs = this.refs;
      // for(var i=0 ;i<refs.length; i++){
      //   var itemParam = this.refs.zbmx_zbdanhang_0.reloadSubItemParam();
      // }
    });
   
  }


  //添加明细
  detailAdd(){
    var form = this.props.form; //表单元素
    var itemParam = this.state.itemParam; //表单元素
    var data = this.props.data; //表单数据
    //var subTblList = data.subTbl;
    // for(var i=0; i<subTblList.length; i++){
    //   if(subTblList[i].subTblName == itemParam.key){
    //     var subModel = this.state.subModel;
    //     subTblList[i].subTblData.push(subModel);
    //   }
    // }
    var subFormList = itemParam.subForm;
    var formItem = form.children;
    if(itemParam.isCopy == false){//子表在新增数据时是否复制默认数据,默认是复制
      formItem.map(function(item){
        item.value='';
        item.defaultValue='';
      });
    }
    var subForm = {show:true,form:formItem};
    subFormList.push(subForm);

    var value = itemParam.value;
    var status = this.props.status;
    if(status == '0'){
      value.push({mainTblData:[],mainTblName:itemParam.key});
    }else{
      value.push({mainTblData:[{key:'id',value:'',required:false}],mainTblName:itemParam.key});
    }
    
    //this.addSubForm(formItem,itemParam,subTblList);
    //value.push({mainTblData:[],mainTblName:itemCode});
    //data.subTbl = subTbl;
    this.setState({
      itemParam:itemParam,
    });
  }

  //新增明细处理数据
  addSubForm(formItem,itemParam,subTblList){
    
    var itemCode = itemParam.key;
    var value = itemParam.value;
    subFormList.push(subForm);
    itemParam.subForm = subFormList;
    //value.push({mainTblData:[],mainTblName:itemCode});
    // for(var i=0; i<subTblList.length; i++){
    //   if(subTblList[i].subTblName == itemParam.key){
    //     var subModel = this.state.subModel;
    //     subTblList[i].subTblData.push({mainTblData:[],mainTblName:itemCode});
    //   }
    // }
    return value;
  }


  getDetai(){
    let t =this;
    var subForm = this.state.itemParam.subForm;
    if(!subForm){
      subForm=[];
    }
    return subForm.map((item, i) => {
      return (
        <div className="dd-drug-list">
          <HBox className="t-BCf dd-bottom-border" onClick={this.detailShow.bind(this,i,item.show)}>
            <Box  className="t-LH44 t-PL16 t-PR2"><i className={item.show?"iconfont icon-arrow-down t-FS18 t-FCc":"iconfont icon-arrow-up t-rotate-90 t-FS18 t-FCc"} ></i></Box>
            <Box flex={1} className="t-LH46 t-FC9" >{i+1}</Box>
            <Box data-key={i} onClick={this.detailDel.bind(this,i)} className={t.state.itemParam.subtableReadonly || subForm.length==1?'t-DN':'t-P16 t-FCddblue'}>删除</Box>
          </HBox>
          <div className={item.show ?"":"t-DN"}>
            {
              item.form.map((item2, j) => {
                return (
                    <Form keyNo={i} ref={item2.uniqueName+'_'+i} dataType="sub" module={t.state.module} status={t.state.status} form={item2}  data={t.state.itemParam.value[i]} fieldControll={t.state.fieldControll}  onChange={this.changeSub.bind(this,this.state.itemParam,i)}/>
                  )}
              )
            }
          </div>
          </div>
        )
      });
  }

  render() {
    const t = this;
    return (
      <div className={t.state.itemParam.isHidden?'t-DN':''}>
        <div className="t-BCf7 t-H10"></div>
        <HBox className="t-P16 t-FS16 t-BCf dd-bottom-border" onClick={this.detailShowAll.bind(this)}>
          <Box flex={1}><span>{t.state.itemParam.title}{t.state.name}</span></Box>
          <Box className="t-FCddblue">
          <i className={this.state.itemParam.show?"iconfont icon-arrow-down t-FS18 t-FCc":"iconfont icon-arrow-up t-rotate-90 t-FS18 t-FCc"} ></i>
          </Box>
        </HBox>
        <div className={this.state.itemParam.show?"":'t-DN'} >
        {this.getDetai()}
        </div>
        <div  onClick={this.detailAdd.bind(this)} className={t.state.itemParam.subtableReadonly?'t-DN':''}>
            <Button type="secondary" display="banner"  >
              <i className="iconfont icon-plus"></i>
              <span>{this.state.itemParam.detailAction}</span>
            </Button>
        </div>
        <div className="t-BCf7 t-H10"></div>
      </div>

    )
  }
}

